package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicWarehouseInventoryDO;
import com.cssy.xxkj.logic.entity.LogicWhCheckTaskDO;
import com.cssy.xxkj.logic.entity.LogicWhCheckTaskItemDO;
import com.cssy.xxkj.logic.service.ILogicWarehouseInventoryService;
import com.cssy.xxkj.logic.service.ILogicWhCheckTaskService;
import com.cssy.xxkj.logic.util.ExcelUtils;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.exception.SyCodeException;

/**
 * 盘点任务controller
 * @author zeyong.gui
 *
 */
@Controller
@RequestMapping("/logic/checkTask")
public class WhCheckTaskController extends BaseController<LogicWhCheckTaskDO> {
	
	private static final String MANAGER = "/xxkj/logic/whchecktask/TaskManager";
	private static final String EIDT = "/xxkj/logic/whchecktask/TaskOperation";

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Resource(name="logicWhCheckTaskService")
	private ILogicWhCheckTaskService logicWhCheckTaskService; 
	
	@Resource(name = "logicWarehouseInventoryService")
	private ILogicWarehouseInventoryService logicWarehouseInventoryService;

	@Override
	public String manager(HttpServletRequest request, Model model)//新建盘点任务
			throws Exception {
		String zdType = request.getParameter("zdType");
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("zdType", zdType);
		String ctType = request.getParameter("ctType");
		model.addAttribute("ctType", ctType);
		return MANAGER;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String zdType = request.getParameter("zdType");
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions taskScs = new SearchConditions();
		hander.getWheres(taskScs);	
		if("task".equals(zdType)){
			//盘点任务
			List<String> billStQuery = Arrays.asList(
					BillStatusUtil.WH_CHECK_TASK_ZERO,
					BillStatusUtil.WH_CHECK_TASK_ONE,
					BillStatusUtil.WH_CHECK_TASK_FIVE);
			taskScs.addCondition("zd003TaskStatus", billStQuery);
		}
		if("make".equals(zdType)){
			taskScs.addCondition("zd003TaskStatus", BillStatusUtil.WH_CHECK_TASK_ONE, SearchCondition.OP_EQUAL);
		}
		if("ckIn".equals(zdType)){
			taskScs.addCondition("zd003TaskStatus", BillStatusUtil.WH_CHECK_TASK_TWO, SearchCondition.OP_EQUAL);
		}
		if(StringUtils.isBlank(taskScs.getOrderBy())){
			taskScs.setOrderBy("bizCreatorDate desc");
		}
		//获得当前用户拥有权限的仓库
		Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request,  scUserRolePlaceService,"zd001WhCode");
		taskScs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		//判断盘点类型
		String ctType = request.getParameter("ctType");
		if("0".equals(ctType)){//月度盘点
			taskScs.addCondition("zd009BillType", BillStatusUtil.MONTHCHECK);
		}
		if("1".equals(ctType)){//日常盘点
			taskScs.addCondition("zd009BillType", BillStatusUtil.EVERDAYCHECK);
		}
		SearchResult result =logicWhCheckTaskService.findListByExample(taskScs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
					throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
			String ctType = request.getParameter("ctType");
			model.addAttribute("ctType", ctType);
		} else {
			LogicWhCheckTaskDO lpd=logicWhCheckTaskService.findListById(id);
			model.addAttribute("pd", lpd);
			if (lpd.getZd009BillType().equals(BillStatusUtil.MONTHCHECK)) {
				model.addAttribute("ctType", "0");
			}
			if (lpd.getZd009BillType().equals(BillStatusUtil.EVERDAYCHECK)) {
				model.addAttribute("ctType", "1");
			}
		}
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return EIDT;
	}
	
	//去盘点
	@RequestMapping("/checkTask")
	public String checkTask(HttpServletRequest request, Model model)throws Exception{
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("zdType","ckIn");
		String taskIdStr = request.getParameter("taskIdStr");
		if(StringUtils.isNotBlank(taskIdStr)){
			String[] taskIds = taskIdStr.split(",");
			for(String checkId : taskIds){
				if(StringUtils.isBlank(checkId)){
					continue;
				}
				LogicWhCheckTaskDO checkTask = logicWhCheckTaskService.findListById(checkId);
				if(checkTask==null){
					continue;
				}
				checkTask.setZd003TaskStatus(BillStatusUtil.WH_CHECK_TASK_TWO);
				logicWhCheckTaskService.update(checkTask, SessionUtil.getUser(request));
			}
		}
		
		return MANAGER;
	}

	@RequestMapping("/gridItems")
	public void gridItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions taskScs = new SearchConditions();
		taskScs.setRemovedProperty(null);
		hander.getWheres(taskScs);
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			taskScs.addCondition("zd001TaskId", id, SearchCondition.OP_EQUAL);
			//名称 编码
			String orderBy="zd002MaterCode ,zd002MaterName ,  zd002MaterModel , zd002MaterSpec , zd002MaterColor , zd002MaterQuality ";
			taskScs.setOrderBy(orderBy);//名称 编码 
			List<LogicWhCheckTaskItemDO> checkTaskItemList = logicWhCheckTaskService.findItemListByExample(taskScs);
			OutJsonGrid out = new OutJsonGrid(checkTaskItemList);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicWhCheckTaskDO curAP, BindingResult result, Model model)
					throws SyBaseException, SyCodeException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String checkdata = request.getParameter("checkdata");
		if (checkdata == null && "".equals(checkdata)) {
			bodyMap.isFail();
			bodyMap.configWebInfor("盘点内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			logicWhCheckTaskService.checkTaskSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicWhCheckTaskDO ld=logicWhCheckTaskService.findListById(field);
				if (ld != null) {
					ld.setRemoved(1l);
					logicWhCheckTaskService.update(ld, SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 根据出库code，查询该仓库的物料库存
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("whTaskMater")
	public void whTaskMater(HttpServletRequest request, HttpServletResponse response)
			throws Exception{
		String whCode = request.getParameter("whCode");
		if(StringUtils.isNotBlank(whCode)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("whCode", whCode);
			List<LogicWarehouseInventoryDO> whInventoryList = logicWarehouseInventoryService.findWareHouseStockByMap(paramMap);
			List<LogicWhCheckTaskItemDO> taskItemList = new ArrayList<LogicWhCheckTaskItemDO>();
			if(whInventoryList==null||whInventoryList.isEmpty()||whInventoryList.size()==0){
				
			}else{
				for(LogicWarehouseInventoryDO whInventory : whInventoryList){
					if(whInventory==null||StringUtils.isBlank(whInventory.getId())){
						continue;
					}
					if(StringUtils.isEmpty(whInventory.getZd009Quantity()+"")||whInventory.getZd009Quantity().compareTo(BigDecimal.ZERO)==0){
						continue;
					}
					LogicWhCheckTaskItemDO taskItem = new LogicWhCheckTaskItemDO();
					taskItem.setZd002MaterId(whInventory.getZd003MaterialsId());//物料id
					taskItem.setZd002MaterCode(whInventory.getZd004MaterialsCode());//物料编码
					taskItem.setZd002MaterName(whInventory.getZd005MaterialsName());//物料名称
					taskItem.setZd002MaterModel(whInventory.getZd007MaterialsModel());//型号
					taskItem.setZd002MaterSpec(whInventory.getZd006MaterialsSpec());//规格
					taskItem.setZd002MaterColor(whInventory.getZd008MaterialsColor());//颜色
					taskItem.setZd002MaterQuality(whInventory.getZd008MaterialsQuanlity());//材质
					taskItem.setZd003Unit(whInventory.getZd008Unit());//单位
					taskItem.setZd006HsQuantity(whInventory.getZd009Quantity());//数量
					taskItem.setZd004Batch(whInventory.getZd020Batch());//batch
					taskItem.setZd005Price(whInventory.getZd024Price());//单价
					taskItem.setZd011PiCode(whInventory.getZd026PiCode());//picode
					taskItem.setZd013OldCustomerID(whInventory.getZd028CustomerID());//客户
					taskItem.setZd013OldCustomerCode(whInventory.getZd028CustomerCode());
					taskItem.setZd013OldCustomerName(whInventory.getZd028CustomerName());
					taskItem.setZd012CustomerName(whInventory.getZd028CustomerName());
					taskItem.setZd012CustomerCode(whInventory.getZd028CustomerCode());
					taskItem.setZd012CustomerID(whInventory.getZd028CustomerID());
					taskItem.setZd011NewPiCode(whInventory.getZd026PiCode());
					taskItem.setZd006HsTaskQuantity(whInventory.getZd009Quantity());//盘点数
					taskItemList.add(taskItem);
				}
			}
			OutJsonGrid out = new OutJsonGrid(taskItemList);
			out.printJSon(response);
		}
	}
	
	@RequestMapping("/exportExcel")
	public void exportAll(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SearchConditions taskScs= new SearchConditions();
		String taskid= request.getParameter("taskid");
		if(StringUtils.isNotBlank(taskid)){
			taskScs.addCondition("zd001TaskId", taskid, SearchCondition.OP_EQUAL);
			String orderBy="zd002MaterCode ,zd002MaterName ,  zd002MaterModel , zd002MaterSpec , zd002MaterColor , zd002MaterQuality ";
			taskScs.setOrderBy(orderBy);
			taskScs.setRemovedProperty(null);
		}else{
			throw new SyBaseException("请导出保存完整的单据");
		}
		String whName=request.getParameter("whName");
		if(whName==null){
			throw new SyBaseException("请导出保存完整的单据");
		}
		whName=new String(whName.getBytes("ISO8859-1"),"UTF-8");
		List<LogicWhCheckTaskItemDO> checkTaskItemList = logicWhCheckTaskService.findItemListByExample(taskScs);
		new ExcelUtils().toExcel(checkTaskItemList, "物料编码:zd002MaterCode┋物料名称:zd002MaterName┋"
				+ "型号:zd002MaterModel┋规格:zd002MaterSpec┋"
				+ "颜色:zd002MaterColor┋材质:zd002MaterQuality┋单位:zd003Unit┋"
				+ "pi编号:zd011PiCode┋库存数量:zd006HsQuantity┋"
				+ "盘点数量:zd006HsTaskQuantity┋差异数量:zd006HsCyQuantity",whName+"盘点任务",response);
		
	}
}

